package com.example;

import com.alibaba.fastjson.JSONObject;
import com.example.model.Person;

import javax.persistence.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ExampleMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        EntityManager em = emf.createEntityManager();
        persistPersons(em);
        findAllPersons(em);
        System.err.println(String.join("", Collections.nCopies(50,"-")));
        moveToHistory(em,1);
        findAllPersons(em);
        System.err.println(String.join("", Collections.nCopies(50, "-")));
        em.close();
        emf.close();
    }

    private static void moveToHistory(EntityManager em,Integer personId){
        StoredProcedureQuery storedProcedureQuery = em.createStoredProcedureQuery("move_to_history");
        storedProcedureQuery.registerStoredProcedureParameter("person_id",Integer.class,ParameterMode.IN);
        storedProcedureQuery.registerStoredProcedureParameter("status_out",Boolean.class,ParameterMode.OUT);
        storedProcedureQuery.setParameter("person_id",personId);
        storedProcedureQuery.execute();
        boolean statusOut = (boolean) storedProcedureQuery.getOutputParameterValue("status_out");
        System.err.println("Out status:" + statusOut);
    }
    private static void findAllPersons(EntityManager em){
        Query query = em.createQuery("select p from Person p",Person.class);
        List<Person> persons = query.getResultList();
        for (Person person : persons) {
            System.err.println(JSONObject.toJSONString(person,false));
        }
    }
    private static void persistPersons(EntityManager em){
        Person person1 = new Person("Dana","Whitley","464 Gorsuch Drive");
        Person person2 = new Person("Robin","Cash","64 Zolla Park");
        Person person3 = new Person("Chary","Mess","112 Yellow Holl");
        em.getTransaction().begin();
        em.persist(person1);
        em.persist(person2);
        em.persist(person3);
        em.getTransaction().commit();
    }
    private static void nativeQuery(EntityManager em,String s){
        System.err.println("--------------" + s + "----------------------");
        Query query = em.createNativeQuery(s);
        List list = query.getResultList();
        for (Object o : list) {
            if (o instanceof Object[]) {
                System.err.println(Arrays.toString((Object[])o));
            }else{
                System.err.println(o);
            }
        }
    }
}
